import { UserConfig, readConfig, defaultConfig } from './config'
import chalk from 'chalk'
import { build } from './build'
import { createServer } from './server'

const argv = require('minimist')(process.argv.slice(2), {
	string: ['port'],
	default: {
		port: 3000 
	}
})

const command = argv._[0]

// init default config
const config: UserConfig = defaultConfig();

(async() => {
	if (!command) {
		logHelp()
		process.exit(1)
	}
	try {
		const userConfig = await readConfig()
		Object.assign(config, userConfig)
	} catch (e) {
		/* handle error */
		console.debug(
			chalk.cyan(e)
		)
	}
	if (command === 'serve') {
		runServer(config)
	} else if (command === 'build') {
		runBuild(config)
	} else {
		logHelp()
		process.exit(1)
	}
})()

// run server
function runServer(options:  UserConfig) {
	const server = createServer(options)
	// on bottom for listen
	server.listen(options.port, function(err, address) {
		if (err) {
			console.error(err)
			process.exit(1)
		}
		console.info(`tserve is listening on ${address}`)
	})
}

// use rollup to build page
function runBuild(options: UserConfig) {
	build(options)
}

function logHelp() {
	console.log(chalk.cyan(`
Use:
	tserve serve 
or
	tserve build

options
--port	The port of devServer (only for tserve serve)
						`
	))
}
